package controllers;

import java.io.File;
import java.io.UnsupportedEncodingException;

import models.User;
import other.Utils;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;

public class Index extends Controller {

    final static Form<User> loginForm = Form.form(User.class);

    public static Result index() {
        if (session().containsKey("user")) {
            return ok(views.html.User.index.render(User.find.byId(Long.valueOf(session().get("user"))).getUsername()));
        }
        return ok(views.html.index.render(loginForm, ""));
    }

    public static Result login() throws UnsupportedEncodingException {
        Form<User> filledLoginForm = loginForm.bindFromRequest();
        if (filledLoginForm.hasErrors()) {
            return badRequest(views.html.index.render(filledLoginForm, ""));
        } else {
            User user = filledLoginForm.get();
            user = User.find.where().eq("userName", user.getUsername())
                    .eq("password", Utils.getSaltedPassword(user.getPassword())).findUnique();
            if (user != null) {
                session().put("user", user.getId().toString());
                session().put("isAdmin", Boolean.toString(user.isAdmin()));
                if (user.getApiAccess().size() > 0) {
                    session().put("keyId", user.getApiAccess().get(0).getKeyId().toString());
                    session().put("vCode", user.getApiAccess().get(0).getvCode());
                }
                return redirect("/");
            } else {
                return badRequest(views.html.index.render(filledLoginForm, "Wrong username/password"));
            }
        }
    }

    public static Result logout() {
        session().clear();
        return redirect("/");
    }

    public static Result displayPicture(String name) {
        File image = new File("public/images/pictures/" + name);
        if (image.exists()) {
            return ok(image);
        } else {
            return ok("No picture with this name !");
        }
    }
}